<!--日程-->
<template>
  <view class="my-schedule">
    <NavBar
      v-if="appInfoStore().isH5"
      title="我的日程"
      :backgroundColor="'#fff'"
    />
    <view
      class="my-schedule-contiainer"
      :class="{ 'padding-top-navbar': appInfoStore().isH5 }"
    >
      <view class="my-schedule-date-box">
        <view class="schedule-contiainer-date">
          <view class="schedule-date-one">
            <view class="schedule-data-one-left">
              <view class="today-week-box">
                <text>{{ todayWeek }}</text>
                <text>今天有{{ dayCount }}个日程安排 </text>
              </view>
              <!-- <view
                class="history-box"
                
              >
                <text>历史{{ isSchedule ? "日程" : "会议" }}<i class="iconfont icon-youjiantou1"></i></text>
              </view> -->
            </view>
            <view class="schedule-data-one-right">
              <i
                class="iconfont icon-rilishijian"
                @click="handleHistory"
              ></i>
              <i class="iconfont icon-sousuo"></i>
            </view>
          </view>
          <view class="schedule-date-two">
            <view class="date-two-swiper">
              <nut-swiper
                class="list-date-two-swiper"
                :init-page="page"
                :loop="true"
                ref="swiper"
                :display-multiple-items="5"
                :width="56"
              >
                <nut-swiper-item
                  v-for="item in weekList"
                  :key="item"
                  @click="handleSwiperItem(item)"
                  :class="{ active: item.isSelect }"
                >
                  <view class="date-two-swiper-item">
                    <text>{{ item.name }}</text>
                    <text>{{ item.today }}</text>
                    <text>
                      <i
                        class="i1"
                        v-if="item.hasPendingMeeting"
                      ></i>
                      <i
                        class="i2"
                        v-if="item.hasOngoingMeeting"
                      ></i>
                      <i
                        class="i3"
                        v-if="item.hasStartingSoonMeeting"
                      ></i>
                      <i
                        class="i4"
                        v-if="!item.hasPendingMeeting && !item.hasOngoingMeeting && !item.hasStartingSoonMeeting"
                      ></i>
                    </text>
                  </view>
                </nut-swiper-item>
              </nut-swiper>
              <view
                class="nut-swiper-btns"
                style="width: 100%"
              >
                <span
                  class="nut-swiper-btns__left"
                  @click="handlePrev"
                >
                  <i class="iconfont icon-zuojiantou"></i>
                </span>
                <span
                  class="nut-swiper-btns__left"
                  @click="handleNext"
                >
                  <i class="iconfont icon-youjiantou1"></i>
                </span>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="my-schedule-box">
        <view
          class="add-schedule-btn"
          @click="goAddMeeting"
        >
          <i class="iconfont icon-jiajianzujianjiahao"></i>
        </view>
        <view class="schedule-list">
          <view class="schedule-list-item">
            <nut-tabs
              v-model="activeTab"
              :swipeable="true"
            >
              <template v-slot:titles>
                <view
                  class="schedule-list-item-title"
                  v-for="tabs in tabs"
                  :key="tabs.id"
                  @click="handleTabs(tabs.id)"
                >
                  <view
                    class="schedule-title"
                    :class="{ active: tabs.id == activeTab }"
                  >
                    <text class="week-text">{{ tabs.title }}</text>
                    <view
                      class="week-num"
                      v-if="tabs.id == 0"
                    >
                      （<text>{{ meetingsPerformTotal.length }} </text> /{{ meetingsTotal.length }}）
                    </view>
                  </view>
                </view>
              </template>
              <nut-tab-pane
                v-for="tab in tabs"
                :key="tab.id"
                :pane-key="tab.id"
              >
                <view class="meeting-list">
                  <!-- 根据条件循环每天的会议 -->
                  <view class="meeting-list-item">
                    <view class="meeting-list-item-day">今天</view>
                    <!-- 根据状态显示endActive redActive greenActive 和不加，四个状态样式-->
                    <view v-if="meetingSchedule.todayMeetings ? meetingSchedule.todayMeetings.length > 0 : false">
                      <template
                        v-for="(item, index) in meetingSchedule.todayMeetings"
                        :key="index"
                      >
                        <view
                          v-for="(itm, idx) in item.meetings"
                          :key="idx"
                          :class="itm.dictStatusClass"
                          class="meeting-list-item-box"
                          @click="goMeetingDetail(itm)"
                        >
                          <view class="meeting-item-left">
                            <text>{{ itm.timeStr }}</text>
                            <nut-divider
                              direction="vertical"
                              style="width: 1px; height: 50px; margin: 10px 0"
                            />
                            <text>{{ itm.timeStrEnd }}</text>
                          </view>
                          <view class="meeting-item-right">
                            <view class="meeting-details">
                              <view class="meeting-details-time">
                                <text class="meeting-item-time">{{ itm.statusDesc }}</text>
                                <view class="meeting-details-more">
                                  <view
                                    v-if="itm.showPopover"
                                    class="popover"
                                  >
                                    <!-- :style="popoverStyle" -->
                                    <view class="popover-content">
                                      <view
                                        class="popover-btn"
                                        @click.stop="handleEdit(itm)"
                                        >编辑</view
                                      >
                                      <view
                                        class="popover-btn"
                                        @click.stop="gohandleDelete(itm)"
                                        >删除</view
                                      >
                                    </view>
                                  </view>
                                  <i
                                    class="iconfont icon-sangediandian"
                                    @click.stop="handleShowMore(itm)"
                                  ></i>
                                </view>
                              </view>
                              <view class="meeting-details-text">
                                <text>{{ itm.subject }}</text>
                              </view>
                              <view class="meeting-details-user">
                                <view class="user">
                                  <view class="user-title">发起人</view>
                                  <view class="user-name">
                                    <img
                                      :src="itm.promoterAvatar"
                                      alt=""
                                    />
                                    <view class="user-name-text">{{ itm.promoterName }}</view>
                                  </view>
                                </view>
                                <view class="meeting-room">
                                  <i class="iconfont icon-address"></i>
                                  <text class="meeting-room-name">{{ itm.position }}</text>
                                  <view
                                    class="meeting-room-number"
                                    v-if="!isSchedule"
                                  >
                                    <nut-divider direction="vertical" />
                                    <text>{{ itm.number }}人</text>
                                  </view>
                                </view>
                              </view>
                            </view>
                          </view>
                        </view>
                      </template>
                    </view>
                    <view
                      class="no-meetings"
                      v-else
                    >
                      <view class="no-meetings-text">没有待开的会议</view>
                    </view>
                  </view>
                  <!-- 明天 -->
                  <view class="meeting-list-item">
                    <view class="meeting-list-item-day">明天</view>
                    <!-- 根据状态显示endActive redActive greenActive 和不加，四个状态样式-->
                    <view v-if="meetingSchedule.tomorrowMeetings ? meetingSchedule.tomorrowMeetings.length > 0 : false">
                      <template
                        v-for="(item, index) in meetingSchedule.tomorrowMeetings"
                        :key="index"
                      >
                        <view
                          v-for="(itm, idx) in item.meetings"
                          :key="idx"
                          :class="itm.dictStatusClass"
                          class="meeting-list-item-box"
                          @click="goMeetingDetail(itm)"
                        >
                          <view class="meeting-item-left">
                            <text>{{ itm.timeStr }}</text>
                          </view>
                          <view class="meeting-item-right">
                            <view class="meeting-details">
                              <view class="meeting-details-time">
                                <text class="meeting-item-time">{{ itm.statusDesc }}</text>
                                <view class="meeting-details-more">
                                  <view
                                    v-if="itm.showPopover"
                                    class="popover"
                                  >
                                    <!-- :style="popoverStyle" -->
                                    <view class="popover-content">
                                      <view
                                        class="popover-btn"
                                        @click.stop="handleEdit(itm)"
                                        >编辑</view
                                      >
                                      <view
                                        class="popover-btn"
                                        @click.stop="gohandleDelete(itm)"
                                        >删除</view
                                      >
                                    </view>
                                  </view>
                                  <i
                                    class="iconfont icon-sangediandian"
                                    @click.stop="handleShowMore(itm)"
                                  ></i>
                                </view>
                              </view>
                              <view class="meeting-details-text">
                                <text>{{ itm.subject }}</text>
                              </view>
                              <view class="meeting-details-user">
                                <view class="user">
                                  <view class="user-title">发起人</view>
                                  <view class="user-name">
                                    <img
                                      :src="itm.promoterAvatar"
                                      alt=""
                                    />
                                    <view class="user-name-text">{{ itm.promoterName }}</view>
                                  </view>
                                </view>
                                <view class="meeting-room">
                                  <i class="iconfont icon-address"></i>
                                  <text class="meeting-room-name">{{ itm.position }}</text>
                                  <view
                                    class="meeting-room-number"
                                    v-if="!isSchedule"
                                  >
                                    <nut-divider direction="vertical" />
                                    <text>{{ itm.number }}人</text>
                                  </view>
                                </view>
                              </view>
                            </view>
                          </view>
                        </view>
                      </template>
                    </view>
                    <view
                      class="no-meetings"
                      v-else
                    >
                      <view class="no-meetings-text">没有待开的会议</view>
                    </view>
                  </view>
                  <!-- 未来一周 -->
                  <view class="meeting-list-item">
                    <view class="meeting-list-item-day">{{
                      meetingSchedule.futureMeetings?.length > 0
                        ? meetingSchedule.futureMeetings[0]?.dateStr
                        : "未来一周"
                    }}</view>
                    <!-- 根据状态显示endActive redActive greenActive 和不加，四个状态样式-->
                    <view v-if="meetingSchedule.futureMeetings ? meetingSchedule.futureMeetings.length > 0 : false">
                      <template
                        v-for="(item, index) in meetingSchedule.futureMeetings"
                        :key="index"
                      >
                        <view
                          v-for="(itm, idx) in item.meetings"
                          :key="idx"
                          :class="itm.dictStatusClass"
                          class="meeting-list-item-box"
                          @click="goMeetingDetail(itm)"
                        >
                          <view class="meeting-item-left">
                            <text>{{ itm.timeStr }}</text>
                          </view>
                          <view class="meeting-item-right">
                            <view class="meeting-details">
                              <view class="meeting-details-time">
                                <text class="meeting-item-time">{{ itm.statusDesc }}</text>
                                <view class="meeting-details-more">
                                  <view
                                    v-if="itm.showPopover"
                                    class="popover"
                                  >
                                    <!-- :style="popoverStyle" -->
                                    <view class="popover-content">
                                      <view
                                        class="popover-btn"
                                        @click.stop="handleEdit(itm)"
                                        >编辑</view
                                      >
                                      <view
                                        class="popover-btn"
                                        @click.stop="gohandleDelete(itm)"
                                        >删除</view
                                      >
                                    </view>
                                  </view>
                                  <i
                                    class="iconfont icon-sangediandian"
                                    @click.stop="handleShowMore(itm)"
                                  ></i>
                                </view>
                              </view>
                              <view class="meeting-details-text">
                                <text>{{ itm.subject }}</text>
                              </view>
                              <view class="meeting-details-user">
                                <view class="user">
                                  <view class="user-title">发起人</view>
                                  <view class="user-name">
                                    <img
                                      :src="itm.promoterAvatar"
                                      alt=""
                                    />
                                    <view class="user-name-text">{{ itm.promoterName }}</view>
                                  </view>
                                </view>
                                <view class="meeting-room">
                                  <i class="iconfont icon-address"></i>
                                  <text class="meeting-room-name">{{ itm.position }}</text>
                                  <view
                                    class="meeting-room-number"
                                    v-if="!isSchedule"
                                  >
                                    <nut-divider direction="vertical" />
                                    <text>{{ itm.number }}人</text>
                                  </view>
                                </view>
                              </view>
                            </view>
                          </view>
                        </view>
                      </template>
                    </view>
                    <view
                      class="no-meetings"
                      v-else
                    >
                      <view class="no-meetings-text">没有待开的会议</view>
                    </view>
                  </view>
                </view>
              </nut-tab-pane>
            </nut-tabs>
          </view>
        </view>
      </view>
    </view>
    <nut-dialog
      title="确定删除？"
      content="确定删除本条数据？"
      v-model:visible="visible1"
      @cancel="onCancel"
      @ok="handleDelete"
    />
  </view>
</template>

<script setup lang="ts">
import NavBar from "@/components/navBar/index.vue";
import { appInfoStore } from "@/stores/appInfo";
import { navigateTo, navigateBack, useRouter, useDidShow } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import { onMounted, ref, Ref, watch, reactive, computed } from "vue";
import { getMeetingSchedule, getDictDataTypeList, deleteMeeting } from "@/api/index";
const router = useRouter();
const isSchedule = ref(true); // 是否是日程
const page = ref(0);
const tabs = ref([
  { id: 0, title: "本周" },
  { id: 1, title: "我发起的" },
]);
const show1 = ref(false);
const show2 = ref(false);
const dayCount = ref(0);
const meetingsTotal = ref([]); //全部
const meetingsPerformTotal = ref([]); //进行中
// 当天
const todayWeek = ref("");
const activeTab = ref(0);
const weekList = ref([]);
const swiper = ref(null) as Ref;
const meetingSchedule = ref([]);
const meetingDictList = ref([]);
const visible1 = ref(false);
watch(isSchedule, val => {
  let myTitle = "我的日程"; //自定义标题
  if (router.params.isSMType == "1") {
    myTitle = "我的日程";
  } else {
    myTitle = "我的会议";
  }
  Taro.setNavigationBarTitle({
    title: myTitle,
  });
});
onMounted(() => {
  isSchedule.value = router.params.isSMType == "1" ? true : false;
  getDictMeetingPurviewFun("meeting_status"); // 获取字典
  getMeetingScheduleList();
  getTodayWeek();
  getWeekList();
});
useDidShow(() => {
  getMeetingScheduleList();
  getTodayWeek();
  getWeekList();
});
const goAddMeeting = () => {
  navigateTo({
    url: "/packageA/pages/workbenches/addSchedule/index?isSMType" + router.params.isSMType,
  });
};
const handleEdit = (itm: any) => {
  navigateTo({
    url: "/packageA/pages/workbenches/addSchedule/index?id=" + itm.id,
  });
};
const selectedMeetingId = ref("");
const gohandleDelete = (itm: any) => {
  visible1.value = true;
  selectedMeetingId.value = itm.id;
};
// 删除
const handleDelete = () => {
  deleteMeeting(selectedMeetingId.value).then(res => {
    if (res.code == 200) {
      Taro.showToast({
        title: "删除成功",
        icon: "none",
      });
      getMeetingScheduleList();
    }
  });
};
// 更多
const buttonRect = reactive({
  top: 0,
  right: 0,
  width: 0,
  height: 0,
});
const handleShowMore = (itm: any) => {
  if (!itm.showPopover) {
    // 获取按钮位置信息
    itm.showPopover = true;
    console.log(buttonRect, "buttonRect");
  } else {
    itm.showPopover = false;
  }
};

//
const handleTabs = (index: number) => {
  activeTab.value = index;
  getMeetingScheduleList();
};
// 去历史
const handleHistory = () => {
  navigateTo({
    url: "/packageB/pages/historyMeetSchedule/index?isSchedule=" + isSchedule.value,
  });
};
// 获取当天的这一周的日期
const getWeekList = () => {
  const now = new Date();
  let days = now.getDay() || 7; // 将周日(0)转换为7
  const weekLists = [];
  for (let i = 1; i <= 7; i++) {
    const date = new Date(now);
    date.setDate(now.getDate() - (days - i));
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    weekLists.push({
      id: i,
      name: ["日", "一", "二", "三", "四", "五", "六"][date.getDay()],
      date: `${year}-${month}-${day}`,
      today: `${day}`,
    });
  }
  weekList.value = weekLists;
};
// 获取当天日期和周
const getTodayWeek = () => {
  // 获取今天的日期和今天是周几(周几是语文数字），示例：2023-12-12（周二）
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, "0");
  const day = String(today.getDate()).padStart(2, "0");
  const week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  todayWeek.value = `${year}-${month}-${day}（${week[today.getDay()]}）`;
};
// meeting_status
// 字典获取（会议提醒）
const getDictMeetingPurviewFun = async dictType => {
  await getDictDataTypeList(dictType).then(res => {
    if (dictType == "meeting_status") {
      meetingDictList.value = JSON.parse(JSON.stringify(res.data));
    }
  });
};
// 获取日程会议列表
const getMeetingScheduleList = async () => {
  meetingSchedule.value = [];
  meetingsTotal.value = [];
  meetingsPerformTotal.value = [];
  // 获取本周的开始日期和结束日期
  const { start, end } = getWeekRange();
  await getMeetingSchedule({ startTime: formatDate(start), endTime: formatDate(end), type: 1 }).then(res => {
    meetingSchedule.value = res.data;
    meetingSchedule.value?.todayMeetings.map((item: any) => {
      item.meetings.map((itm: any) => {
        itm.dictStatusClass = "";
        itm.showPopover = false;
        if (itm.meetingState == 0) {
          itm.dictStatusClass = "";
        } else if (itm.meetingState == 1) {
          itm.dictStatusClass = "greenActive";
        } else if (itm.meetingState == 2) {
          itm.dictStatusClass = "endActive";
        } else if (itm.meetingState == 3) {
          itm.dictStatusClass = "endActive";
        }
      });
    });
    // if (!type) {
    meetingSchedule.value.todayMeetings?.forEach((item: any) => {
      meetingsTotal.value.push(...item.meetings);
    });
    meetingSchedule.value.tomorrowMeetings?.forEach((item: any) => {
      meetingsTotal.value.push(...item.meetings);
    });
    meetingSchedule.value.weekMeetings?.forEach((item: any) => {
      meetingsTotal.value.push(...item.meetings);
    });
    meetingsPerformTotal.value = meetingsTotal.value.filter((item: any) => item.meetingState == 1); // 进行中的会议
    // }
    weekList.value.map(itm => {
      meetingSchedule.value?.meetingCounts.forEach((res: { date: any; count: any }) => {
        if (res.date.split("-")[2] == itm.today) {
          itm = Object.assign(itm, res);
        }
      });
    });
    console.log(weekList.value, "weekList.value");
  });
};
const handlePrev = () => {
  swiper.value.prev();
};
const handleNext = () => {
  swiper.value.next();
};
const handleSwiperItem = (item: any) => {
  // 选中的样式
  weekList.value.map(itm => {
    itm.isSelect = itm.id == item.id ? true : false;
  });
  todayWeek.value = item.date + "（周" + item.name + "）";
  getDayCount(item.hasOngoingMeeting, item.hasPendingMeeting, item.hasStartingSoonMeeting);
};
const getDayCount = (hasOngoingMeeting, hasPendingMeeting, hasStartingSoonMeeting) => {
  const counts = computed(() => {
    return [hasOngoingMeeting, hasPendingMeeting, hasStartingSoonMeeting].filter(Boolean).length; // 过滤出 true 并计算长度
  });
  dayCount.value = counts.value;
};
// 去详情
const goMeetingDetail = (itm: any) => {
  navigateTo({
    url: "/packageB/pages/meetingDetail/index?id=" + itm.id + "&isSMType=" + router.params.isSMType,
  });
};
function getWeekRange() {
  const now = new Date();
  const day = now.getDay() || 7; // 将周日(0)转换为7
  const start = new Date(now);
  start.setDate(now.getDate() - day + 1); // 本周一
  start.setHours(0, 0, 0, 0);
  const end = new Date(start);
  end.setDate(start.getDate() + 6); // 本周日
  end.setHours(23, 59, 59, 999);
  return { start, end };
}
function formatDate(date) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}
</script>

<style lang="less">
@import "./index.less";
// @import "../../../../assets/css/index.css";
@import "@/assets/css/index.less";
</style>
